package com.kun.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.common.constant.RedisConstant;
import com.kun.common.service.RedisService;
import com.kun.common.util.JsonUtils;
import com.kun.domain.TUserMoments;
import com.kun.service.mapper.TUserMomentsMapper;
import com.kun.service.service.ITUserMomentsService;
import com.kun.service.util.UserContext;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TUserMomentsServiceImpl extends ServiceImpl<TUserMomentsMapper, TUserMoments> implements ITUserMomentsService {

    private final RocketMQTemplate rocketMQTemplate;
    private final RedisService redisService;

    @Value("${rocketmq.consumer.topic}")
    private String topic;

    public TUserMomentsServiceImpl(RocketMQTemplate rocketMQTemplate, RedisService redisService) {
        this.rocketMQTemplate = rocketMQTemplate;
        this.redisService = redisService;
    }

    /**
     * 发布动态
     */
    @Override
    public Boolean addUserMoments(TUserMoments tUserMoments) {
        tUserMoments.setUserId(UserContext.getUserId());
        tUserMoments.setCreateTime(LocalDateTime.now());
        boolean save = save(tUserMoments);
        rocketMQTemplate.convertAndSend(topic, tUserMoments);
        return save;
    }

    /**
     * 查询当前用户订阅的内容
     */
    @Override
    public List<TUserMoments> getSubscribed() {
        String key = redisService.getKey(RedisConstant.USER_FANS_KEY + UserContext.getUserId());
        return JsonUtils.toList(key, TUserMoments.class);
    }
}
